package attendance

import (
	"encoding/json"
	"errors"
	"fmt"
	"net/url"

	"gitee.com/suguo79/xyh"
	"github.com/google/uuid"
)

// 上传考勤（学校ID和用户ID）
// https://open.api.xiaoyuanhao.com/access_center/attendance/create_with_user?access_token=ACCESS_TOKEN
func AttendanceClockin(au []*AttendanceUserRequest) (*AttendanceUserResponse, error) {
	reqbody := &AttendanceRequest{
		TransactionID: uuid.Must(uuid.NewUUID()).String(),
		Data:          au,
	}

	token, err := xyh.RefreshAccessToken()
	if err != nil {
		return nil, err
	}

	opt := url.Values{}
	opt.Add("access_token", *token)

	payload, err := xyh.HttpRequestWithoutHeader("access_center/attendance/create_with_user", opt, reqbody)
	if err != nil {
		return nil, err
	}

	data := &AttendanceUserResponse{}
	if err := json.Unmarshal(*payload, &data); err != nil {
		return nil, err
	}
	return data, nil
}

// 获取学校下用户信息
// https://open.api.xiaoyuanhao.com/access_center/user/list_page?access_token=ACCESS_TOKEN&org_id=ORG_ID&index=INDEX
func AttendanceUserList(orgid, role string) ([]*AttendanceUsers, error) {
	idx := 0
	result := make([]*AttendanceUsers, 0)
	for {
		idx++
		token, err := xyh.RefreshAccessToken()
		if err != nil {
			return nil, err
		}

		opt := url.Values{}
		opt.Add("access_token", *token)
		opt.Add("org_id", orgid)
		opt.Add("index", fmt.Sprintf("%d", idx))
		payload, err := xyh.HttpRequestWithoutHeader("access_center/user/list_page", opt, nil)
		if err != nil {
			return nil, err
		}

		data := &AttendanceUserListResponse{}
		if err := json.Unmarshal(*payload, &data); err != nil {
			return nil, err
		}
		if data.Code != 0 {
			return nil, errors.New(data.Msg)
		}

		if role == "" {
			result = append(result, data.Data.Users...)
		}

		if role != "" {
			for _, usr := range data.Data.Users {
				if usr.UserType == role {
					result = append(result, usr)
				}
			}
		}
		if data.Data.HasNext == 0 {
			break
		}
	}
	return result, nil
}
